#!/usr/bin/python

# make-profile.py
# Generate a KML profile given a pile of coordinates.
# 
# Copyright Borkware 2010 . All rights reserved.


# make-profile.py - slurp in a LineString coordinates, and blort out
# something that'll make a google earth profile.

# arguments:
#    -R : reverse path?  (YES | NO)

import getopt
import math
import sys


try:
    opts, args = getopt.getopt(sys.argv[1:], 'R:')
except getopt.GetoptError, err:
    print "oops - not enough args in getopt"
    sys.exit(1)

reverse_path = False

for o, a in opts:
    if o == '-R':
        if a == "YES":
            reverse_path = True
        else:
            reverse_path = False

playback_smoothness = 0.0002

# read coordinates from standard-in
raw_coords = sys.stdin.read()
raw_coords = raw_coords.lstrip('\n')
raw_coords = raw_coords.lstrip(' ')
raw_coords = raw_coords.rstrip('\n')
raw_coords = raw_coords.rstrip(' ')

string_coords = raw_coords.split(" ")

if reverse_path:
    string_coords.reverse()

coords = []
last_coord = None
i = 0
for s in string_coords:
    coord = s.split(",")
    c = (float(coord[1]), float(coord[0]))
    coords.append(c)


import json
import urllib
import glineenc

ELEVATION_BASE_URL = 'http://maps.google.com/maps/api/elevation/json'

def getElevation(path, samples="200", sensor="false", **elvtn_args):
    encode = glineenc.encode_pairs(path)

    elvtn_args.update({
        'path': "enc:" + encode[0],
        'samples': samples,
        'sensor': sensor
    })

    url = ELEVATION_BASE_URL + '?' + urllib.urlencode(elvtn_args)

    response = json.load(urllib.urlopen(url))

    # Create a dictionary for each results[] object
    elevationArray = []

    for resultset in response['results']:
      elevationArray.append(resultset['elevation'])

    return elevationArray


# limit it to 450 coords
count = len(coords)
start = 0
if count < 450:
    stop = count
else:
    stop = 450

# TODO - scale the number of samples to the number of points.
# right now, if there's overflow, you'll get N*samples
total_profile = []
while True:
    if start > stop:
        break
    profile = getElevation (coords[start:stop], samples = granularity)
    total_profile.extend(profile)
    start = stop + 1
    stop = start + 450
    if stop > count: stop = count

for p in total_profile:
    print "%d" % p
